/*
	后台-用户控制器
*/
'use strict';
var moment		= require('moment');
var AV 				= require('leanengine');
var mdCommon	= require('../modules/common');


/**
 * 用户列表页面
 * 2015.04.18  by 胡斌
 */
exports.listPage = function(req, res) {
	var pager,where=" objectId is exists",urlParam="",param={};
	var adminRole		= req.query.role;
	var search			= req.query.search;

	if(typeof(adminRole)!="undefined" && adminRole.length>0){
		where	+= ' and adminRole is exists';
	}else{
		where	+= ' and adminRole is not exists';
	}
	if(typeof(search)!="undefined" && search.length>0){
		//console.log(search);
		search=search.replace(/(^\s*)|(\s*$)/g, "");
		if(search.length>0){
			where	+= " and (username like '%"+search+"%' or displayName like '%"+search+"%')";
		}
		param['search']=search;
		urlParam+="&search="+search;
	}
	//console.log('select count(*) from _User where'+where);
	AV.Query.doCloudQuery('select count(*) from _User where'+where).then(function(data){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, data.count);
		return AV.Query.doCloudQuery('select * from _User where'+where+' limit '+(pager.currentPage-1)*pager.pagesize+','+pager.pagesize);
	}).then(function(data) {
		res.render('admin-user-list.html',{
			user:req.AV.user,
			results:data.results,
			moment:moment,
			pager:pager,
			adminRole:adminRole,
			urlParam:urlParam,
			param:param
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 用户详情页面
 * 2015.05.14  by 胡斌
 */
exports.detailPage = function(req, res) {
	var queryUser 	= new AV.Query(AV.User);
	var id					= req.query.id;

	queryUser.get(id).then(function(result) {
		res.render('admin-user-detail.html',{
			user:req.AV.user,
			result:result,
			moment:moment
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 新增用户
 * 2015.04.18  by 胡斌
 */
exports.doCreate = function(req,res) {
	var User;
	var name				= req.body.name;
	var email				= req.body.email;
	var displayName	= req.body.displayName;
	var queryUser 	= new AV.Query(AV.User);
	queryUser.equalTo("username",name);
	queryUser.count().then(function(count){
		if(count>0){
			return AV.Promise.error('该用户名已存在！');//
		}else{
			queryUser 	= new AV.Query(AV.User);
			queryUser.equalTo("email",email);
			return queryUser.count();
		}
	}).then(function(count){
		if(count>0){
			return AV.Promise.error("该邮箱已存在！");
		}else{
			var newUser 	= new AV.User();
			newUser.set("password",req.body.password);
			newUser.set("username",name);
			newUser.set("email",email);
			newUser.set("emailVerified",true);
			newUser.set("displayName",displayName);
			newUser.set("adminRole","admin");
			return newUser.save();
		}
	}).then(function(Role) {
		res.redirect('/admin/user/list?role=admin');
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 用户管理-保存
 * 2015.05.15  by 胡斌
 */
exports.doSaveUser = function(req, res) {
	var User;
	var id			= req.body.id;
	var roleName	= req.body.roleName;
	var queryUser 	= new AV.Query(AV.User);
	if(typeof(id)=="undefined")id=-1;

	//console.log("id"+id);
	queryUser.equalTo("objectId",id);
	queryUser.first().then(function(result) {
		if(typeof(result)=="undefined"){
			return AV.Promise.error('用户不存在！');//
		}else if(result.id==req.AV.user.id){
			return AV.Promise.error('无法修改自身账号！');//
		}else if(result.get("protected")){
			return AV.Promise.error('无法修改受保护用户！');//
		}else{
			User			= result;
			var queryRole 	= new AV.Query(AV.Role);
			queryRole.containedIn("name",[roleName,User.get("roleName")]);
			return queryRole.find();
		}
	}).then(function(results){
		if(results.length<1 || (results.length==1 && results[0].get("name")!=roleName)){
			return AV.Promise.error('角色不存在！');//
		}else{
			console.dir("results.length="+results.length);
			console.dir(results[1]);

			if(results.length>1 && results[0].get("name")!=results[1].get("name")){
				if(results[0].get("name")==roleName){
					results[0].getUsers().add(User);
					results[1].getUsers().remove(User);
				}else{
					results[1].getUsers().add(User);
					results[0].getUsers().remove(User);
				}
				return AV.Promise.all([results[0].save(),results[1].save()]);
			}else{
				return AV.Promise.all([]);
			}
		}
	}).then(function(result){
		if(req.body.password.length>0){
			var crypto 	= require('crypto');
			var md5 	= crypto.createHash('md5');
			md5.update(req.body.password);
			User.set("password",md5.digest('hex'));
		}
		if(req.body.email!=User.get("email")){
			User.set("email",req.body.email);
		}
		User.set("username",req.body.username);
		User.set("roleName",roleName);
		return User.save();
	}).then(function(result) {
		if(req.body.ajax){
			res.json({result:result});
		}else{
			res.redirect('/admin/user/list');
		}
	},function(error){
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 删除用户
 * 2015.05.02  by 胡斌
 */
exports.doDelete = function(req, res) {
	var role;
	var id			= req.body.id;
	var queryUser 	= new AV.Query(AV.User);
	if(typeof(id)=="undefined")id="-1";

	queryUser.select("objectId","protected","adminRole");
	queryUser.equalTo("objectId",id);
	queryUser.first().then(function(user){
		if(typeof(user)=="undefined"){
			return AV.Promise.error('用户不存在！');//
		}else if(user.id==req.AV.user.id){
			return AV.Promise.error('无法删除自身账号！');//
		}else if(user.get("protected")){
			return AV.Promise.error('无法删除受保护用户！');//
		}else{
			role	= user.get("adminRole");
			console.log(role);
			return user.destroy();
		}
	}).then(function(User) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			//console.log(typeof(role));
			if(typeof(role)=="undefined"){
				res.redirect('/admin/user/list');
			}else{
				res.redirect('/admin/user/list?role=admin');
			}
		}
  },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}
